<template>
  <div class="imgs-upload" v-loading.fullscreen.lock="loading">
    <template v-for="(imgUrl,index) in imgUrls">
      <img-upload v-if="!readonly||(readonly&&imgUrl.url!=='')" ref="imgUpload" :key="imgUrl.id" v-model="imgUrl.url" :auto-upload="autoUpload"
        :drag="drag" :upload-check-method="uploadCheckMethod" :error-msg="errorMsg" :img-handle="imgHandle"
        :readonly="readonly||readonlyImg.indexOf(imgUrl.url)!==-1" :has-full-loading="!autoUpload" :img-width="imgWidth" :img-height="imgHeight"
        @delete="deleteImg(index)" @change="uploadChange" @upload-success="uploadSuccess">
      </img-upload>
    </template>
  </div>
</template>

<script>
  import SystemUtil from 'utils/systemUtil';

  import ImgUpload from './imgUpload';

  export default {
    props: {
      value: {
        type: Array,
        required: true
      },
      imgWidth: [String, Number],
      imgHeight: [String, Number],
      readonly: {
        type: Boolean,
        default: false
      },
      readonlyImg: {
        type: Array,
        default: () => []
      },
      autoUpload: {
        type: Boolean,
        default: true
      },
      drag: {
        type: Boolean,
        default: false
      },
      uploadCheckMethod: Function,
      errorMsg: {
        type: String,
        default: '请选择图片格式文件上传'
      },
      imgHandle: {
        type: Array,
        default () {
          return ['preview', 'delete'];
        }
      },
      limit: {
        type: Number,
        default: 0
      }
    },

    watch: {
      value() {
        if (this.inputValue !== null) {
          this.inputValue = null;
          return;
        }
        this.imgUrls = this.getImgUrls();
      }
    },

    data() {
      return {
        loading: false,
        inputValue: null,
        imgUrls: this.getImgUrls()
      };
    },

    methods: {
      getImgUrls() {
        let value = this.value;
        let imgUrls = _.map(value, imgUrl => {
          return {
            id: SystemUtil.getId(),
            url: imgUrl
          };
        });

        let limit = this.limit;
        if (limit === 0 || imgUrls.length < limit) {
          imgUrls.push({
            id: SystemUtil.getId(),
            url: ''
          });
        }
        return imgUrls;
      },

      deleteImg(index) {
        let imgUrls = this.imgUrls;
        imgUrls.splice(index, 1);

        if (imgUrls.length === 0) {
          imgUrls.push({
            id: SystemUtil.getId(),
            url: ''
          });
        } else {
          let obj = imgUrls[imgUrls.length - 1];
          if (obj.url !== '') {
            imgUrls.push({
              id: SystemUtil.getId(),
              url: ''
            });
          }
        }
        this.imgsChange();
      },

      addImg() {
        let imgUrls = this.imgUrls;
        let limit = this.limit;
        if (limit === 0 || imgUrls.length < limit) {
          imgUrls.push({
            id: SystemUtil.getId(),
            url: ''
          });
        }
      },

      uploadChange(file, type) {
        if (!this.autoUpload) {
          if (type === 'add') {
            this.addImg();
          }
        }
      },

      uploadSuccess() {
        if (this.autoUpload) {
          this.addImg();
          this.imgsChange();
          return;
        }
      },

      imgsChange() {
        let imgUrls = this.imgUrls;
        let urls = [];
        for (let i = 0; i < imgUrls.length; i++) {
          let imgUrl = imgUrls[i];
          let url = imgUrl.url;
          if (url !== '') {
            urls.push(url);
          }
        }

        this.inputValue = urls;
        this.$emit('input', urls);
        this.$emit('change', urls);
      },

      submit() {
        let imgUploads = this.$refs['imgUpload'];
        let promiseList = [];
        for (let i = 0; i < imgUploads.length; i++) {
          let imgUpload = imgUploads[i];
          promiseList.push(imgUpload.submit());
        }

        this.loading = true;
        return Promise.all(promiseList).then(res => {
          this.imgsChange();
          this.loading = false;
          return res;
        }).catch(error => {
          this.loading = false;
          throw error;
        });
      }
    },

    components: {
      ImgUpload
    }
  };

</script>

<style lang="scss" scoped>
  .imgs-upload {
    display: flex;
    flex-wrap: wrap;
    justify-content: start;
    align-items: center;

    >.img-upload {
      margin-right: 10px;
      margin-bottom: 10px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

</style>
